package sd.qd.xiaoming.coffeedesk.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import sd.qd.xiaoming.coffeedesk.entity.CdNote;
import sd.qd.xiaoming.coffeedesk.service.CdNoteService;
import sd.qd.xiaoming.coffeedesk.service.CdNoteTypeService;

@Controller
@RequestMapping("/note")
public class CdNoteController {

    @Autowired
    private CdNoteService cdNoteService;
    @Autowired
    private CdNoteTypeService cdNoteTypeService;

    @ResponseBody
    @RequestMapping("delete_note/{id}")
    public Object deleteNote(@PathVariable("id") final Long id) {
        this.cdNoteService.delete(this.cdNoteService.findById(id));
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        return result;
    }
    
    @ResponseBody
    @RequestMapping("/get_note/{id}")
    public Object getNote(@PathVariable("id") final Long id){
        CdNote result = this.cdNoteService.findById(id);
        result.setType(null);
        return result;
    }

    @ResponseBody
    @RequestMapping("/get_note_by_type")
    public Object getNoteByType(@RequestParam("type_id") final Long typeId) {
        List<CdNote> result = this.cdNoteTypeService.findById(typeId)
                .getNotes();
        for (CdNote note : result) {
            note.setType(null);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("save_note")
    public Object saveNote(
            @RequestParam(value = "id", required = false) final Long id,
            @RequestParam("type_id") final Long typeId,
            @RequestParam("title") final String title,
            @RequestParam("content") final String content) {
        CdNote note = new CdNote();
        note.setTitle(title);
        note.setNoteJson(content);
        note.setTime(new Date());
        note.setAlertEnabled(false);
        note.setDateEnableld(false);//TODO 日期时间
        note.setType(this.cdNoteTypeService.findById(typeId));
        Map<String, Object> result = new HashMap<String, Object>();
        if(null==id){
            this.cdNoteService.save(note);
            result.put("msg", "新建便签成功！");
        } else {
            note.setId(id);
            this.cdNoteService.update(note);
            result.put("msg", "修改便签成功！");
        }
        result.put("success", true);
        return result;
    }

}
